/**
 * API调用辅助工具
 * 统一处理API响应、错误处理、数据格式化
 */

/**
 * 统一的API调用包装器
 * @param {Function} apiCall - API调用函数
 * @param {Object} options - 配置选项
 * @param {Function} options.onSuccess - 成功回调
 * @param {Function} options.onError - 错误回调
 * @param {Function} options.dataProcessor - 数据处理函数
 * @param {boolean} options.showLoading - 是否显示加载状态
 * @param {Object} options.context - 页面上下文
 */
const safeApiCall = async (apiCall, options = {}) => {
  const {
    onSuccess,
    onError,
    dataProcessor,
    showLoading = false,
    context
  } = options;

  try {
    if (showLoading && context) {
      context.setData({ loading: true });
    }

    const response = await apiCall();

    if (response && response.code === 200) {
      let data = response.data;
      
      // 数据处理
      if (dataProcessor && typeof dataProcessor === 'function') {
        data = dataProcessor(data);
      }

      if (onSuccess) {
        await onSuccess(data);
      }

      return { success: true, data };
    } else {
      throw new Error(response?.message || '请求失败');
    }
  } catch (error) {
    console.error('API调用失败:', error);
    
    if (onError) {
      onError(error);
    }

    return { success: false, error: error.message };
  } finally {
    if (showLoading && context) {
      context.setData({ loading: false });
    }
  }
};

/**
 * 小说数据处理器
 * 确保小说数据字段完整性
 */
const processNovelData = (novel) => {
  if (!novel) return null;
  
  return {
    ...novel,
    likeCount: novel.likeCount || 0,
    commentCount: novel.commentCount || 0,
    favoriteCount: novel.favoriteCount || 0,
    currentChapterCount: novel.currentChapterCount || 0,
    targetChapterCount: novel.targetChapterCount || null,
    participants: novel.participants || [],
    isParticipant: novel.isParticipant || false,
    creatorNickname: novel.creatorNickname || '匿名',
    tags: novel.tags || '',
    description: novel.description || '',
    coverUrl: novel.coverUrl || '',
    status: novel.status || 1,
    creationType: novel.creationType || 1
  };
};

/**
 * 小说列表数据处理器
 */
const processNovelList = (novels) => {
  if (!Array.isArray(novels)) return [];
  
  return novels.map(processNovelData);
};

/**
 * 评论数据处理器
 */
const processCommentData = (comment) => {
  if (!comment) return null;
  
  return {
    ...comment,
    user: {
      ...comment.user,
      avatar: comment.user?.avatar || '/static/default-avatar.png',
      nickname: comment.user?.nickname || '匿名用户'
    },
    replies: comment.replies ? comment.replies.map(processCommentData) : [],
    createdAt: comment.createdAt || '',
    content: comment.content || ''
  };
};

/**
 * 评论列表数据处理器
 */
const processCommentList = (comments) => {
  if (!Array.isArray(comments)) return [];
  
  return comments.map(processCommentData);
};

/**
 * 分页数据处理器
 */
const processPaginationData = (response, currentList = [], isLoadMore = false) => {
  const data = response.data || {};
  const list = data.list || data || [];
  
  return {
    list: isLoadMore ? [...currentList, ...list] : list,
    hasMore: data.hasMore || list.length >= (data.pageSize || 10),
    total: data.total || 0,
    page: data.page || 1,
    pageSize: data.pageSize || 10
  };
};

/**
 * 通用错误处理
 */
const handleApiError = (error, context, defaultMessage = '操作失败，请重试') => {
  console.error('API错误:', error);
  
  if (context && context.selectComponent) {
    // 显示错误消息
    const message = context.selectComponent('#t-message');
    if (message) {
      message.error({
        content: error.message || defaultMessage
      });
    }
  }
};

/**
 * 互动操作辅助函数（点赞、收藏等）
 */
const createInteractionHelper = (context, dataPath) => {
  return {
    /**
     * 点赞操作
     */
    async toggleLike(apiCall, isLiked, likeCount) {
      const newIsLiked = !isLiked;
      const newLikeCount = newIsLiked ? likeCount + 1 : Math.max(0, likeCount - 1);
      
      // 立即更新UI
      context.setData({
        [`${dataPath}.isLiked`]: newIsLiked,
        [`${dataPath}.likeCount`]: newLikeCount
      });

      try {
        await apiCall();
      } catch (error) {
        // 回滚UI状态
        context.setData({
          [`${dataPath}.isLiked`]: isLiked,
          [`${dataPath}.likeCount`]: likeCount
        });
        handleApiError(error, context, '点赞失败，请重试');
      }
    },

    /**
     * 收藏操作
     */
    async toggleFavorite(apiCall, isFavorited, favoriteCount) {
      const newIsFavorited = !isFavorited;
      const newFavoriteCount = newIsFavorited ? favoriteCount + 1 : Math.max(0, favoriteCount - 1);
      
      // 立即更新UI
      context.setData({
        [`${dataPath}.isFavorited`]: newIsFavorited,
        [`${dataPath}.favoriteCount`]: newFavoriteCount
      });

      try {
        await apiCall();
      } catch (error) {
        // 回滚UI状态
        context.setData({
          [`${dataPath}.isFavorited`]: isFavorited,
          [`${dataPath}.favoriteCount`]: favoriteCount
        });
        handleApiError(error, context, '收藏失败，请重试');
      }
    }
  };
};

module.exports = {
  safeApiCall,
  processNovelData,
  processNovelList,
  processCommentData,
  processCommentList,
  processPaginationData,
  handleApiError,
  createInteractionHelper
};
